<template>
	<view class="sales">
		<!-- 回到顶部按钮 -->
		<view class="back-to-top" :class="{ 'show-back-top': showBackTop }" @tap="scrollToTop">
			<image
				src="https://hedashepin.oss-cn-guangzhou.aliyuncs.com/upload/3/20250308/7c1cce16799e556a5b8bd4ff1ad0bb58.png"
				mode="aspectFit"></image>
		</view>
		<view class="header-box">
			<view class="header-title">
				<image class="title-img" v-if="opt.type == 1" :src="static_url + '/static/sales/hot_sales.jpg'">
				</image>
				<image class="title-img" v-else :src="static_url + '/static/sales/time_sales.jpg'">
				</image>
			</view>
			<!-- <view class="status_bar" @click="goBack">
				<image src="../../static/img/arrow-right.png" mode=""></image>
			</view> -->
		</view>

		<view class="sales-rank">
			<!-- 固定标题栏 -->
			<view class="fixed-header" :class="{ 'header-fixed': isHeaderFixed }">
				<scroll-view scroll-x :scroll-into-view="scrollToId" scroll-with-animation>
					<view class="header-tabs">
						<view class="tab-item" id="tab-all" :class="{ active: currentTab == 'all' }" :style="{
						                color: currentTab == 'all' ? t('color2') : '',
						                transform: currentTab == 'all' ? 'scale(1.05)' : 'scale(1)',
						                fontWeight: currentTab == 'all' ? 'bold' : 'normal'
						            }" @tap="switchTab('all', { id: '' })">
							全部
						</view>
						<view v-for="(item, index) in tabs" :key="index" :id="'tab-' + item.id" class="tab-item"
							:class="{ active: currentTab == item.id }" :style="{ 
						                color: currentTab == item.id ? t('color2') : '',
						                transform: currentTab == item.id ? 'scale(1.05)' : 'scale(1)',
						                fontWeight: currentTab == item.id ? 'bold' : 'normal'
						            }" @tap="switchTab(item.id, item)">
							{{ item.name }}
						</view>
					</view>
				</scroll-view>
			</view>
			<!-- 原始标题栏 -->
			<view class="rank-header">
				<scroll-view scroll-x :scroll-into-view="scrollToId" scroll-with-animation>
					<view class="header-tabs">
						<view class="tab-item" id="tab-all" :class="{ active: currentTab == 'all' }" :style="{
						                color: currentTab == 'all' ? t('color2') : '',
						                transform: currentTab == 'all' ? 'scale(1.05)' : 'scale(1)',
						                fontWeight: currentTab == 'all' ? 'bold' : 'normal'
						            }" @tap="switchTab('all', { id: '' })">
							全部
						</view>
						<view v-for="(item, index) in tabs" :key="index" :id="'tab-' + item.id" class="tab-item"
							:class="{ active: currentTab == item.id }" :style="{ 
						                color: currentTab == item.id ? t('color2') : '',
						                transform: currentTab == item.id ? 'scale(1.05)' : 'scale(1)',
						                fontWeight: currentTab == item.id ? 'bold' : 'normal'
						            }" @tap="switchTab(item.id, item)">
							{{ item.name }}
						</view>
					</view>
				</scroll-view>
			</view>
			<nodata v-if="showNoData"></nodata>
			<scroll-view v-else class="rank-list" scroll-y>
				<view class="rank-item" v-for="(item, index) in rankList" :key="index" @tap="goToDetail(item)"
					id="item.proid">
					<view class="goods-info">
						<view class="goods-container">
							<image class="goods-img" :src="item.pic" mode="aspectFill"></image>
							<image class="goods-pm" :src="getRankImage(index)" mode="widthFix"></image>
							<view class="rank-num">
								{{ index + 1 }}
							</view>
						</view>
						<view class="goods-detail">
							<view class="goods-hot" :style="{color:t('color2')}" v-if="opt.type ==1">
								销量{{ item.num_count || 0 }}件</view>
							<view class="goods-hot" :style="{color:t('color2')}" v-else>今日热销{{ item.num_count }}件</view>
							<view class="goods-title">{{ item.name }}</view>
							<view class="sales-count" v-if="opt.type != 1">
								<text>已售 {{ item.sales  || 0}}</text>
							</view>
							<view class="coupon-box" :style="{color:t('color2')}" v-if="item.couponlist.length>0">
								<view class="coupon-item-box" :style="{ border: `2rpx solid ${t('color2')}` }"
									v-for="(item, index) in item.couponlist.slice(0, 2)" :key="index">
									<view class="coupon-left" v-if="item.type == 1">
										商品券
									</view>
									<view class="coupon-left" v-if="item.type == 41">
										新人券
									</view>

									<view class="coupon-right">
										{{ item.name }}
									</view>
								</view>
							</view>
							<view class="goods-bottom">
								<view class="price-box" :style="{color:t('color1')}">
									<text class="price-symbol">¥</text>
									<text class="price-value">{{ item.sell_price }}</text>
								</view>
								<view class="price-add" :style="{background:t('color1')}">
									+
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	var app = getApp();
	export default {
		data() {
			return {
				pre_url: app.globalData.pre_url,
				static_url: app.globalData.static_url,
				tabs: [],
				currentTab: 'all',
				rankList: [],
				showNoData: false,
				targetProid: '',
				scrollToId: '',
				isHeaderFixed: false,
				headerHeight: 0,
				showBackTop: false,
				opt: {}
			}
		},
		onLoad(options) {
			if (options) {
				this.opt = options;
			}
			if (options.type == 1) {
				uni.setNavigationBarTitle({
					title: '热销排行榜'
				});
			} else {
				uni.setNavigationBarTitle({
					title: '实时销量榜'
				});
			}
			const {
				cid,
				proid
			} = options;
			this.targetProid = proid;
			// 先获取分类数据
			this.gettags(() => {
				if (cid) {
					this.currentTab = cid;
					this.scrollToId = 'tab-' + cid;
					this.getdata(cid);
				} else {
					this.getdata();
				}
			});
		},
		onPullDownRefresh() {
			if (this.currentTab === 'all') {
				this.getdata();
			} else {
				this.getdata(this.currentTab);
			}


			this.gettags();

			uni.stopPullDownRefresh();
		},
		onPageScroll(e) {
			// 监听页面滚动
			const scrollTop = e.scrollTop;
			// 当滚动超过header高度时，固定header
			this.isHeaderFixed = scrollTop > this.headerHeight;
			// 当滚动超过500px时显示回到顶部按钮
			this.showBackTop = scrollTop > 500;
		},
		onReady() {
			// 获取header高度
			const query = uni.createSelectorQuery().in(this);
			query.select('.header-box').boundingClientRect(data => {
				if (data) {
					this.headerHeight = data.height;
				}
			}).exec();
		},
		methods: {
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			getRankImage(index) {
				const rank = index + 1; // 转为1-based
				if (rank === 1) return '/pagesSocial/static/img/pm1.png';
				if (rank === 2) return '/pagesSocial/static/img/pm2.png';
				if (rank === 3) return '/pagesSocial/static/img/pm3.png';
				return '/pagesSocial/static/img/pm4.png';
			},
			switchTab(index, item) {
				this.currentTab = index;
				const cid = item.id || '';
				this.scrollToId = 'tab-' + cid;
				this.getdata(cid);
			},
			scrollToTarget() {
				if (!this.targetProid) return;
				setTimeout(() => {
					const index = this.rankList.findIndex(item => item.proid === this.targetProid);
					if (index === -1) return;
					const query = uni.createSelectorQuery().in(this);
					query.select('.rank-list').boundingClientRect();
					query.selectAll('.rank-item').boundingClientRect();
					query.exec((res) => {
						if (!res[0] || !res[1]) return;
						const scrollView = res[0];
						const items = res[1];
						if (index >= items.length) return;
						const item = items[index];
						const scrollTop = item.top - scrollView.top + scrollView.scrollTop;
						// 滚动到指定位置
						this.$nextTick(() => {
							const scrollViewContext = uni.createSelectorQuery().in(this).select(
								'.rank-list');
							scrollViewContext.node().scrollOffset((offset) => {
								scrollViewContext.scrollTo({
									top: scrollTop,
									duration: 300
								});
							}).exec();
						});
					});
				}, 500);
			},
			getdata(cid) {
				const params = {};
				if (cid) params.cid = cid;
				let url = '';
				if (this.opt.type == 1) {
					url = 'DataCount/getshophotsell'
				} else {
					url = 'DataCount/getshopdaysell'
				}
				app.get(url, params, (res) => {
					if (res.code === 200) {
						this.rankList = res.data || [];
						this.showNoData = this.rankList.length === 0;
						if (this.targetProid) {
							this.$nextTick(() => {
								this.scrollToProduct(this.targetProid);
							});
						}
					} else {
						app.error(res.msg);
						this.rankList = [];
						this.showNoData = true;
					}
				});
			},

			// 滚动到指定商品位置
			scrollToProduct(proid) {
				const index = this.rankList.findIndex(item => item.proid === proid);
				if (index === -1) return;

				// 等待DOM渲染完成
				setTimeout(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.rank-list').boundingClientRect();
					query.selectAll('.rank-item').boundingClientRect();
					query.exec((res) => {
						if (!res[0] || !res[1]) return;
						const scrollView = res[0];
						const items = res[1];
						if (index >= items.length) return;

						const item = items[index];
						const scrollTop = item.top - scrollView.top;

						// 获取scroll-view组件实例
						const scrollViewContext = uni.createSelectorQuery().in(this).select('.rank-list');
						scrollViewContext.node().exec((res) => {
							if (res[0] && res[0].node) {
								res[0].node.scrollTo({
									top: scrollTop,
									duration: 300
								});
							}
						});
					});
				}, 300);
			},

			// 获取分类列表
			gettags(callback) {
				app.get('Shop/classify', {
					needinit: 1
				}, (res) => {
					if (res.status === 1) {
						this.tabs = res.data;
						this.$nextTick(() => {
							if (this.currentTab !== 'all') {
								this.scrollToId = 'tab-' + this.currentTab;
								// 确保DOM更新后再执行滚动
								setTimeout(() => {
									const query = uni.createSelectorQuery().in(this);
									query.select('#tab-' + this.currentTab).boundingClientRect();
									query.select('.header-tabs').boundingClientRect();
									query.exec((res) => {
										if (res[0] && res[1]) {
											const tabRect = res[0];
											const containerRect = res[1];
											const scrollLeft = tabRect.left - containerRect
												.left - (containerRect.width - tabRect
													.width) / 2;
											uni.pageScrollTo({
												scrollLeft: scrollLeft,
												duration: 300
											});
										}
									});
								}, 100);
							}
							if (callback) callback();
						});
					} else {
						app.error(res.msg);
						if (callback) callback();
					}
				});
			},
			// 跳转到商品详情
			goToDetail(item) {

				uni.navigateTo({
					url: `/pages/shop/product?id=${item.proid}`
				})
			},
			// 回到顶部方法
			scrollToTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},
		}
	}
</script>

<style>
	.sales {}

	.sales-rank {
		background: #f5f5f5;
		border-radius: 12rpx;
		padding: 20rpx;

	}

	.rank-header {
		padding-bottom: 20rpx;
	}

	.header-title {
		width: 100%;
		height: 400rpx;
		overflow: hidden;
		position: relative;
	}

	.status_bar {
		position: absolute;
		top: 80rpx;
		left: 20rpx;
	}

	.status_bar image {
		width: 80rpx;
		height: 80rpx;
	}

	.title-img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.title-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.nav-tabs {
		white-space: nowrap;
		/* 禁止换行 */
		width: 100%;
		/* 撑满父容器 */
	}



	.rank-list {}

	.rank-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		margin: 20rpx 0;
		background-color: #fff;
		border-radius: 20rpx;
	}



	.goods-info {
		flex: 1;
		display: flex;
	}

	.goods-container {
		position: relative;
	}

	.goods-img {
		width: 240rpx;
		height: 240rpx;
		border-radius: 8rpx;
		margin-right: 10rpx;
	}

	.goods-pm {
		position: absolute;
		top: 0;
		left: 30rpx;
		width: 50rpx;
		height: 50rpx;
	}

	.rank-num {
		position: absolute;
		top: 0;
		left: 30rpx;
		/* 和 goods-pm 对齐 */
		width: 50rpx;
		/* 和 goods-pm 同宽 */
		height: 50rpx;
		/* 和 goods-pm 同高 */
		line-height: 50rpx;
		color: white;
		font-size: 26rpx;
		display: flex;
		align-items: center;
		/* 垂直居中 */
		justify-content: center;
		/* 水平居中 */
		z-index: 2;
		/* 确保文字在图片上方 */
	}

	.goods-detail {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.goods-hot {
		color: #03BC01;
	}

	.goods-title {
		font-size: 26rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
		/* 限制显示两行文字 */
		display: -webkit-box;
		-webkit-line-clamp: 2;
		/* 设置显示的行数 */
		-webkit-box-orient: vertical;
		overflow: hidden;
		/* 超出部分隐藏 */
	}

	.goods-desc {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 10rpx;
	}

	.goods-bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.price-box {
		color: #ff6b81;
	}

	.price-symbol {
		font-size: 24rpx;
	}

	.price-value {
		font-size: 32rpx;
		font-weight: bold;
	}

	.sales-count {
		font-size: 24rpx;
		color: #999;
	}

	.trend-tag {
		display: flex;
		align-items: center;
		font-size: 24rpx;
		padding: 0 20rpx;
	}

	.trend-tag.up {
		color: #ff6b81;
	}

	.trend-tag.down {
		color: #67c23a;
	}

	.trend-tag.stable {
		color: #909399;
	}

	.trend-icon {
		width: 24rpx;
		height: 24rpx;
		margin-left: 6rpx;
	}

	.header-tabs {
		display: flex;
		border-bottom: 1rpx solid #eee;
	}

	.tab-item {
		flex-shrink: 0;
		text-align: center;
		font-size: 28rpx;
		color: #666;
		padding: 20rpx;
		position: relative;
	}

	.coupon-box {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 10rpx;
	}

	.coupon-item-box {
		display: flex;
		align-items: center;
		background: #fff;
		border-radius: 8rpx;
		font-size: 24rpx;
		margin-top: 6rpx;

	}

	.coupon-left {
		padding-right: 6rpx;
		position: relative;
	}

	.coupon-left::after {
		content: '';
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 1rpx;
		height: 80%;
		border-right: 2rpx dashed #ccc;
	}

	.coupon-right {
		padding-left: 6rpx;
	}

	.price-add {
		width: 50rpx;
		height: 50rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 50%;
		font-size: 36rpx;
		color: white;
	}

	.fixed-header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
		background: #f5f5f5;
		transform: translateY(-100%);
		transition: transform 0.3s ease;
	}

	.header-fixed {
		transform: translateY(0);
	}

	.fixed-header .header-tabs {
		background: #f5f5f5;
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
	}

	.back-to-top {
		position: fixed;
		right: 30rpx;
		bottom: 120rpx;
		width: 80rpx;
		height: 80rpx;
		background: #fff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
		opacity: 0;
		transform: translateY(100rpx);
		transition: all 0.3s ease;
	}

	.back-to-top image {
		width: 40rpx;
		height: 40rpx;
	}

	.show-back-top {
		opacity: 1;
		transform: translateY(0);
	}
</style>